<template>
  <uni-forms-item label="验证码" name="code" required>
    <view class="captcha-item">
      <uni-easyinput v-model="state.captcha" placeholder="请输入验证码" @change="finishTypeCaptcha"></uni-easyinput>
      <view class="uni-mx-5">
        <button :disabled="state.formConf.disableReqCaptcha" @tap="clickReqCaptcha" size="mini" type="warn">{{state.formConf.captchaTxt}}</button>
      </view>
    </view>
  </uni-forms-item>
</template>
<script setup lang="ts">
import {onBeforeUnmount, onMounted, ref} from "vue";
import {requireCode} from "@/services/login";

const props = defineProps(['phone'])
const emits = defineEmits(['getCaptcha'])
const state = ref({
  captcha: "",
  formConf: {
    disableReqCaptcha: false,
    captchaTxt: "获取验证码",
    reqTime: 0,
    intervalId: 0,
    remainTime: 60000
  }
})

const finishTypeCaptcha = () => {
  console.log("ready send captcha data to parent component")
  emits('getCaptcha', state.value.captcha)
}
const clickReqCaptcha = () => {
  console.log(props.phone)
  if (props.phone) {
    uni.showToast({
      title: `验证码已发送，${(state.value.formConf.remainTime / 1000).toFixed(0)} 秒后可重新获取`,
      icon: "none"
    })
    // 获取验证码
    requireCode(props.phone).then((r) => {
      state.value.formConf.reqTime = Date.now()
      disableReqCaptcha()
    }).catch(() => {})

    return
  }
  uni.showToast({
    title: '请输入正确的手机号',
    icon: "none"
  })
}

const createInterval = () => {
  state.value.formConf.intervalId = setInterval(() => {
    disableReqCaptcha()
  }, 1000)
}

/**
 * 判断是否禁用获取验证码按钮
 */
const disableReqCaptcha = () => {
  const remainTime = state.value.formConf.remainTime
  console.log("计算是否请求验证码组件的可用性")
  if (state.value.formConf.reqTime === 0) {
    state.value.formConf.disableReqCaptcha = false
    return
  }
  const timestamp = Date.now()
  const timeAfterReq = timestamp - state.value.formConf.reqTime
  state.value.formConf.disableReqCaptcha = timeAfterReq < remainTime
  const timOfCountdown = ((remainTime - timeAfterReq) / 1000).toFixed(0)
  if (state.value.formConf.disableReqCaptcha) {
    state.value.formConf.captchaTxt = `${timOfCountdown} 秒`
    return;
  }
  state.value.formConf.captchaTxt = "获取验证码"
  state.value.formConf.disableReqCaptcha = false
}

onMounted(() => {
  createInterval()
})

onBeforeUnmount(() => {
  console.log("组件销毁前")
  clearInterval(state.value.formConf.intervalId)
})
</script>
<style scoped lang="scss">
.captcha-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .req-captcha {
    color: #e43d33
  }
}
</style>